package com.zhuhjay.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuhjay.eduservice.entity.EduChapter;
import com.zhuhjay.eduservice.entity.EduVideo;
import com.zhuhjay.eduservice.entity.chapter.ChapterVo;
import com.zhuhjay.eduservice.entity.chapter.VideoVo;
import com.zhuhjay.eduservice.mapper.EduChapterMapper;
import com.zhuhjay.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.eduservice.service.EduVideoService;
import com.zhuhjay.servicebase.exception.GuLiException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ZhuHJay
 * @since 2022-09-06
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {

    @Resource
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
        List<ChapterVo> list = new ArrayList<>();
        // 查询该课程的章节信息
        List<EduChapter> chapters = this.list(new LambdaQueryWrapper<EduChapter>()
                .eq(EduChapter::getCourseId, courseId));

        // 查询单个章节的小节信息
        for (EduChapter chapter : chapters) {
            // 添加到列表
            ChapterVo chapterVo = new ChapterVo().setId(chapter.getId()).setTitle(chapter.getTitle());
            list.add(chapterVo);
            // 根据章节查询小节
            List<EduVideo> videos = videoService.list(new LambdaQueryWrapper<EduVideo>()
                    .eq(EduVideo::getChapterId, chapterVo.getId()));
            for (EduVideo video : videos) {
                chapterVo.getChildren().add(new VideoVo(video.getId(), video.getTitle(), video.getVideoSourceId()));
            }
        }
        return list;
    }

    @Override
    public void removeIfNotVideo(String chapterId) {
        // 如果章节下有小节，不让删除
        int count = videoService.count(new LambdaQueryWrapper<EduVideo>()
                .eq(EduVideo::getChapterId, chapterId));
        if (count > 0) {
            throw new GuLiException(20001, "删除失败，请先删除小节信息");
        }
        this.removeById(chapterId);
    }
}
